import os

from yl_pms import utils


def process_data(pid):
    """处理原始数据，即把rabbitmq的exchange名的后缀改为当前项目名
    raw.yaml:原始数据文件
    data.yaml:修改后的数据文件
    """
    fr = 'pms/fixtures/raw.yaml'
    fw = 'pms/fixtures/data.yaml'
    file_data = ""
    ps = utils.MysqlUtil.get_ps(pid)
    if ps is not None:
        with open(fr, "r", encoding="utf-8") as f:
            for line in f:
                line = line.replace('ex_wlf', 'ex_{}'.format(ps))
                file_data += line
        with open(fw, "w", encoding="utf-8") as f:
            f.write(file_data)
        return fw
    else:
        raise ValueError('未查询到该工程：{}'.format(pid))


def load_data(pid):
    """为模型提供初始化的数据"""
    # 先处理数据
    fw = process_data(pid)
    cmd = 'python3 manage.py loaddata data.yaml --settings=yl_pms.settings.settings_{}'.format(pid)
    os.system(cmd)
    msg = 'origin data load success'
    os.remove(fw)
    utils.print_info(msg)


def rm_cache():
    """删除缓存"""
    cache_dir = 'pms/migrations/'
    init_file = '__init__.py'
    li = os.listdir(cache_dir)
    for f in li:
        file_path_rm = cache_dir + f
        if f != init_file and os.path.isfile(file_path_rm):
            os.remove(file_path_rm)
    msg = 'cache rm success'
    utils.print_info(msg)


def init(pid):
    # 创建数据模型
    cmd1 = 'python3 manage.py makemigrations --settings=yl_pms.settings.settings_{}'.format(pid)
    os.system(cmd1)
    msg = 'virtual model create success'
    utils.print_info(msg)

    # 创建真实的数据表
    cmd2 = 'python3 manage.py migrate --settings=yl_pms.settings.settings_{}'.format(pid)
    os.system(cmd2)
    msg = 'real model create success'
    utils.print_info(msg)

    # 为模型提供初始化的数据
    load_data(pid)

    # 创建超级管理员【需手动】
    msg = '\033[1;32;41mPlease run the following command to create a superuser manually !\033[0m'
    print(msg)
    cmd3 = 'python3 manage.py createsuperuser --settings=yl_pms.settings.settings_{}'.format(pid)
    msg = '\033[4;34;34m{}\033[0m'.format(cmd3)
    utils.print_info(msg)


if __name__ == '__main__':
    """该脚本需要和manage.py在同一目录
    """
    project_id = '4'
    exec_env = 'prod'
    # utils.MysqlUtil.del_db(project, exec_env)
    # utils.MysqlUtil.create_db(project, exec_env)
    # rm_cache()
    init(project_id)
